<template>
  <!-- 订单支付详情 -->
  <section>
    <div style="border-bottom:1px solid #eee;padding-bottom:10px;">
      <el-page-header @back="goBack" content="账单详情"></el-page-header>
    </div>
    <br />
    <div class="visit_detail_box">
      <div class="userinfo p-sm">
        <p v-if="detail">
          <img v-if="detail.head!=''" :src="detail.head | imageUrl" class="patient_img" alt />
          <img v-else src="/img/unknown-avatar.4f0c79ac.png" class="patient_img" alt />
        </p>
        <p v-if="detail">
          <span style="font-size: 20px; margin-right: 20px; vertical-align: middle;">{{detail.name}}</span>
          <i class="glyphicon glyphicon-earphone" style="vertical-align: middle; font-size: 18px;"></i>
        </p>
        <div v-if="detail" class="user-field">
          <span>性别：</span>
          {{detail.sex | toSex}}
        </div>
        <div v-if="detail" class="user-field">  
          <span>年龄：</span>
          <label v-if="detail.age>17">{{detail.age}}</label>
          <label v-else>{{detail.birthday|toTimeContrast}}</label>
        </div>
        <div v-if="detail" class="user-field">
          <span>门诊号：</span>
          <span style="color: red;">{{detail.archivesCode}}</span>
        </div>
      </div>
      <div class="user-content p-sm">
        <el-row style="margin:10px 0px;display:inline-block;width:100%;">
          <el-col :span="6">
            <label style="font-size:16px;">收费项目</label>
          </el-col>
          <el-col style="height:10px;" :span="6"></el-col>
          <el-col style="height:10px;" :span="6"></el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <table class="table-box">
              <thead>
                <tr>
                  <th>
                    <el-checkbox
                      :indeterminate="isIndeterminate"
                      v-model="checkAll"
                      :disabled="isRemaber"
                      @change="handleCheckAllChange"
                    ></el-checkbox>
                  </th>
                  <th>收费名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>折扣</th>
                  <th>是否套餐抵扣</th>
                  <th>核销数量</th>
                  <th>金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in itemList" :key="index">
                  <template v-if="item.source !='13'">
                    <td v-if="isGo" class="return-item_td">
                      <el-checkbox-group
                        v-model="checkedAdmin"
                        @change="handleCheckedCitiesChange($event,item.sourceId,item.totalAmount,item.actualAmount)"
                      >
                        <el-checkbox :label="item.sourceId" :disabled="(item.packageWriteOff || item.memberGive) ?true:false" :key="item.sourceId"></el-checkbox>
                      </el-checkbox-group>
                    </td>
                    <td>{{item.sourceName}}</td>
                    <td>{{item.unitPrice!=undefined?item.unitPrice:item.oneMoney }}</td>
                    <td>{{item.number?item.number:item.frequency}}</td>
                    <td>{{item.unitName}}</td>
                    <td>
                      <el-input
                       v-if="!item.packageWriteOff"
                        @blur="changeDis(item,1)"
                        :disabled="item.showDis"
                        v-model="item.discount"
                      >
                        <template slot="append">折</template>
                      </el-input>
                      <label v-else>---</label>
                    </td>
                    <td style="text-align:center;">{{item.packageWriteOff?"是":"否"}}</td>
                    <td style="text-align:center;">{{item.packageWriteOffNumber}}</td>
                    <td>
                      <el-input
                       v-if="!item.packageWriteOff"
                       @blur="changeDis(item,2)"
                        v-model="item.actualAmount"
                      >
                        <template slot="prepend">￥</template>
                      </el-input>
                      <label v-else>￥{{item.actualAmount}}</label>
                    </td>
                  </template>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <el-row v-if="tsList.length>0" class="moeny_box" style="margin-top:10px;">
          <el-col class="other" style="height:20px;font-size:16px;margin:5px 0;" :span="24">特殊收费项目</el-col>
          <el-col :span="24">
            <table class="table-box">
              <thead>
                <tr>
                  <th>
                    <el-checkbox
                      :indeterminate="isCombo"
                      :disabled="true"
                      v-model="checkComboAll"
                      @change="changeCombo"
                    ></el-checkbox>
                  </th>
                  <th>收费名称</th>
                  <th>原价</th>
                  <th>数量</th>
                  <th>优惠价</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(it,index) in tsList" :key="index">
                  <td>
                    <el-checkbox-group
                      v-model="checkedCombo"
                      :disabled="true"
                      class="pay_check_box"
                      @change="tsChange($event,it.sourceId,it.actualAmount)"
                    >
                      <el-checkbox :label="it.sourceId" :key="it.sourceId"></el-checkbox>
                    </el-checkbox-group>
                  </td>
                  <td>{{it.sourceName}}</td>
                  <td>￥{{it.totalAmount}}</td>
                  <td>{{it.number}}</td>
                  <td>￥{{it.actualAmount}}</td>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>应收金额：</label>
            <span>￥ {{totalMoney | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>实收金额：</label>
            <span>￥{{total | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row class="money_box">
          <el-col class="other" :span="18"></el-col>
          <el-col class="money" :span="6">
            <label>折扣金额：</label>
            <span>￥{{disAmount | changeMoneyToTwo}}</span>
          </el-col>
        </el-row>
        <el-row style="margin-top:20px;">
          <el-button
            style="float:right;"
            @click="onBeforeSubmit"
            :loading="btnLoading"
          >去结账</el-button>
          <el-button style="float:right;margin-right:10px;" @click="doPrint()">打印</el-button>
        </el-row>
      </div>
      <iframe
        v-if="showOrder"
        frameborder="0"
        height="0px"
        width="0px"
        ref="iframe"
        src="/print/chargerecipe.html"
      ></iframe>
    </div>
  </section>
</template>
<script>
import newBLVue from '../../process/_jz/newBL.vue';
import calculate from '../_js/calculate'
export default {
  name: "chargeDetail",
  data() {
    return {
      dialogRecord: false,
      detail: "",
      checkedAdmin: [],
      checkAll:false,
      isIndeterminate: false,
      isCombo: true,
      checkedCombo: [],
      checkComboAll: [],
      itemList: [],
      tsList: [], //特殊项目
      total: 0,
      totalMoney: 0.0, //总金额
      billPayways: [],
      dwList: [],
      disAmount: 0.0,
      integralNum: 0,
      doctorId: 0,
      deptId: 0,
      deptName:'',
      doctorName:'',
      //套餐二级id
      userPackageItemId:'',
      showOrder: false,
      btnLoading: false,
      isGo: true,
      isRemaber:false,
    };
  },
  created() {
  },
  mounted() {
    this.getBasic();
    this.findUsUserById();
    this.getItemDetail();
    this.isGo = this.$route.query.isOrder ? false : true;
  },
  methods: {
    getItemDetail() {
      let id = this.jieMi(this.$route.query.id);
      this.$api.getNoPayCureDetailList({ cureId: id }).then((res) => {
        if (res.executed) {
           let checked=[];
           const dataList=res.dataBody.items;
           this.doctorId=res.dataBody.doctorId;
           this.deptId=res.dataBody.deptId;
           this.deptName=res.dataBody.deptName,
            this.doctorName=res.dataBody.doctorName,
           //套餐耳机id
           this.userPackageItemId=res.dataBody.comboId;
           let checkedCombo=[];
           let list=[];
           let tsList=[];
           let num=0;
           dataList.forEach(it => {
              if(it.packageWriteOff || it.memberGive){
                num++;
              }
              if(it.source!=13){
                checked.push(it.sourceId);
                list.push({...it,discount:10,packageWriteOffNumbe:it.packageWriteOffNumbe?it.packageWriteOffNumbe:0});
              }else{
                tsList.push({...it,discount:10,packageWriteOffNumbe:it.packageWriteOffNumbe?it.packageWriteOffNumbe:0});
                checkedCombo.push(it.sourceId);
              }
           });
           if(num>0){
             this.isRemaber=true;
           }
           this.checkedCombo = checkedCombo;
           this.checkedAdmin = checked;
           this.checkAll=list.length==checked.length?true:false;
           this.itemList=list;
           this.tsList=tsList;
           let money=dataList.reduce((t,c)=>{
               return t+=c.actualAmount;
           },0);
           this.total=money;
           this.totalMoney=money;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //获取患者详情
    findUsUserById() {
      let th = this;
      let uid = th.jieMi(th.$route.query.patientId);
      th.showLoading();
      th.$api
        .getPatientInfo({ patientId: uid, hpId: th.adminUser.hpId })
        .then((res) => {
          if (res.executed) {
            th.detail = res.dataBody;
            th.active = true;
            th.ispersonal = false;
            th.showLoading(false);
          } else {
            th.showLoading(false);
            th.$message.error(res.message);
          }
        });
    },
    getBasic() {
      let th = this;
      th.getCommonConfigByKey("药品剂量单位").then((res) => {
        th.dwList = res;
      });
    },
    /**
     * 获取折扣数/折后金额
     * @param {type}  1、获取折后价格  2、获取折扣数
     * @param {discount}  折数
     * @param {actualAmount} 优惠价
     * @param {totalAmount} 原价
     */
    changeDis(item,type) {
       let reg=/((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
       if(!reg.test(item.actualAmount)){
          this.$message.warning("请输入正确的实收金额");
          item.actualAmount=item.showAmount;
          return false;
       }
       if(!reg.test(item.discount)){
         this.$message.warning("请输入正确的折扣数");
          item.discount=10;
          item.actualAmount=item.showAmount;
          return false;
       }
       if(item.showAmount<item.actualAmount){
          this.$message.warning("折扣金额不能大于实收金额");
          item.actualAmount=item.showAmount;
          return false;
        }
        const { discount,actualAmount,showAmount } =item;
        if(type==1){
            let numberRule=/^([0-9]|10)(\.([0-9]{1,2}|10))?$/;
            if(!numberRule.test(item.discount)){
                this.$message.warning("请输入0~10以内的折扣数");
                item.actualAmount=item.showAmount;
                item.discount=10;
            }else{
                item.actualAmount=Number(item.showAmount-calculate.disCalculate(10-Number(discount),type)(showAmount)).toFixed(2);
                //  item.actualAmount=Number(calculate.disCalculate(discount,type)(totalAmount)).toFixed(2);
            }
        }else{
            item.discount= calculate.disCalculate(actualAmount,type)(showAmount);
        }
        item.discountAmount=Number(item.showAmount-item.actualAmount).toFixed(2);

        let list=this.itemList.filter(it=>{
            if(this.checkedAdmin.includes(it.sourceId))  return it;
        })
        if(this.checkedAdmin.includes(item.sourceId)){
          let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(list,true);
          let tcObj= calculate.calculateTotalByList(this.tsList);
          this.total=Number(newTotalMoney+tcObj.newTotalMoney);
          this.totalMoney=Number(oldTotalMoney+tcObj.oldTotalMoney);
          this.disAmount=Number(discountMoney+tcObj.discountMoney);
        }
    },
    handleCheckedCitiesChange(value, id,oldMoney, money) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.itemList.length;
      this.isCombo = checkedCount > 0 && checkedCount < this.itemList.length;
      let bools = value.includes(id);
      if(bools){
         this.total+=Number(money);
         this.totalMoney+=Number(money);
         this.disAmount+=Number(oldMoney-money);
      }else{
         this.total-=money;
         this.totalMoney-=money;
         this.disAmount-=(oldMoney-money);
      }
    },
    changeCombo(val) {
    },
    //特殊收费
    tsChange(value, id, money) {
      let checkedCount = value.length;
      this.checkComboAll = checkedCount === this.itemList.length;
      this.isCombo = checkedCount > 0 && checkedCount < this.itemList.length;
      let bools = value.includes(id);
      if (bools == true) {
        this.totalMoney = Number(this.totalMoney) + Number(money);
        this.totalMoney = this.totalMoney.toFixed(2);
      } else {
        this.totalMoney = Number(this.totalMoney) - Number(money);
        this.totalMoney = this.totalMoney.toFixed(2);
      }
    },
    //预先提交提示
    onBeforeSubmit() {
         const list=this.itemList;
         const tcList=this.tsList;
         let items=[];
         if(list.length>0){
           list.map(it=>{
              if(this.checkedAdmin.includes(it.sourceId)){
                delete it.unitName;
                items.push({...it,discount:it.discount!=10?Number(it.discount/10).toFixed(2):''})
              }
           });
         }
         if(tcList.length>0){
           tcList.map(it=>{
              if(this.checkedCombo.includes(it.sourceId)){
                delete it.unitName;
                items.push({...it,discount:''})
              }
            });
         }
         let total=items.reduce((t,c)=>{
           return t+=c.totalAmount;
         },0)
        let param={
            orderItems:JSON.stringify(items),
            actualAmount:Number(this.total).toFixed(2) ,
            patientId:this.detail.patientId,
            source:1,
            totalAmount:Number(total).toFixed(2),
            deptId:this.deptId,
            doctorId:this.doctorId,
            sourceId:this.jieMi(this.$route.query.id),
            userPackageItemId:this.userPackageItemId
        }
         this.$api.createNewOrder(param).then(res=>{
             if(res.executed){
                this.$router.push({
                  path: "/page/paychargeV2",
                  query: this.getUrlToken({id:res.dataBody.orderId})
                });
             }else{
               this.$message.error(res.message);
             }
         })
    },
    goBack() {
      this.$router.go(-1);
    },
    doPrint() {
      this.showOrder = true;
      this.showLoading();
      setTimeout(()=> {
        this.iframeContent = this.$refs.iframe.contentWindow;
        this.iframeContent.postMessage(
          {
            cmd: "postJson",
            params: JSON.stringify({
              detail: this.detail,
              disAmount: Number(this.disAmount).toFixed(2) ,
              list: this.itemList,
              doctor:this.doctorName,
              dept:this.deptName,
              special: this.tsList, //特殊收费
              billPayways: this.billPayways,
              logo: this.adminUser.printLogo,
              orderCode: '',
              total: Number(this.totalMoney).toFixed(2),
              hospitalName: this.adminUser.hospitalName,
            }),
          },
          "*"
        );
      }, 500);
      setTimeout(()=> {
        this.showLoading(false);
      }, 2000);
    },
    handleCheckAllChange(val){
      let checked = [];
      const item=this.itemList;
      for (var i = 0; i < item.length; i++) {
        checked.push(item[i].sourceId);
      }
      this.checkedAdmin = val ? checked : [];
      let ilist=[];
      if (this.checkedAdmin.length > 0) {
        item.forEach(it=>{
          if(checked.includes(it.sourceId)){
            ilist.push(it);
          }
        })
      }else{
        ilist=[];
      }
      let {oldTotalMoney , newTotalMoney , discountMoney} = calculate.calculateTotalByList(ilist)(true);
      let tcObj= calculate.calculateTotalByList(this.tsList);
      this.total=Number(newTotalMoney+tcObj.newTotalMoney);
      this.totalMoney=Number(oldTotalMoney+tcObj.oldTotalMoney);
      this.disAmount=Number(discountMoney+tcObj.discountMoney);
      this.isCombo = false;
    }
  },
};
</script>
<style lang="scss" scoped>
@import "../_css/detail.scss";
.patient_img {
  border: 1px solid #ddd;
  border-radius: 5px;
  display: inline-block;
  width: 100px;
  height: 100px;
}
.durg_title {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.money_box {
  margin-top: 10px;
  display: inline-block;
  width: 100%;
  .other {
    height: 10px;
    display: inline-block;
  }
  .money {
    text-align: right;
    padding-right: 10px;
    display: inline-block;
  }
}
.printOrder {
  display: inline-block;
  width: 100%;
}
</style>

